/**
 * 
 */
package com.servicecloud.fallback;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

/**
 * @Description <br>
 *              设置好了一个zuul失败回退类，实际生产中还是通过hystrix进行服务降级处理<br>
 *              note:该回退类只是通过zuul访问才会返回该错误消息，如果是通过客户端访问服务，那么还是返回hytrix的服务降级固定消息
 * @author Gavin<br>
 *         2019年8月17日
 */
@Component
public class DeptProviderFallback implements ZuulFallbackProvider {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider#
	 * getRoute()
	 */
	@Override
	public String getRoute() {
		// TODO Auto-generated method stub
		return "microservicecloud";// 设置好失败处理的路由
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider#
	 * fallbackResponse()
	 */
	@Override
	public ClientHttpResponse fallbackResponse() {
		// TODO Auto-generated method stub
		return new ClientHttpResponse() {

			@Override
			public HttpHeaders getHeaders() {// 设置返回的头信息
				HttpHeaders headers = new HttpHeaders();
				headers.set("Content-Type", "application/json;charset=UTF-8");
				return headers;
			}

			@Override
			public InputStream getBody() throws IOException {
				// TODO Auto-generated method stub
				return new ByteArrayInputStream(
						"{\"deptno\":111,\"dname\":\"【ERROR】Zuul-Fallback\",\"loc\":\"Zuul Gateway客服端的失败回退处理\"}"
								.getBytes());// 当出现服务调用错误之后返回的数据内容
			}

			@Override
			public String getStatusText() throws IOException {
				// TODO Auto-generated method stub
				return HttpStatus.BAD_REQUEST.getReasonPhrase();
			}

			@Override
			public HttpStatus getStatusCode() throws IOException {
				// TODO Auto-generated method stub
				return HttpStatus.BAD_REQUEST;
			}

			@Override
			public int getRawStatusCode() throws IOException {
				// TODO Auto-generated method stub
				return HttpStatus.BAD_REQUEST.value();
			}

			@Override
			public void close() {
				// TODO Auto-generated method stub

			}
		};
	}

}
